package felix.things.router.mqtt;

import felix.things.router.mqtt.listener.BaseCoverMessageListener;
import felix.things.router.mqtt.listener.PrintMessageListener;
import felix.things.router.mqtt.persistent.PersistentFileService;
import felix.things.router.mqtt.sender.MqttMessageSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.*;

/**
 * @author Felix
 * @date 2019/7/27
 **/
@Component
public class MqttUtils {

    private static final int OPERATION_TIMEOUT_IN_SEC = 10;

    @Autowired
    private MqttBrokerMonitor mqttBrokerMonitor;

    @Autowired
    private PersistentFileService persistentFileService;

    @Autowired
    private MqttMessageSender mqttMessageSender;

    @Value("${mqttrouter.enable:false}")
    private boolean enable;

    @PostConstruct
    private void init() {
        if (enable) {
            ExecutorService pool = new ThreadPoolExecutor(10, 20,
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<>(1024), new ThreadPoolTaskExecutor(), new ThreadPoolExecutor.AbortPolicy());
            pool.execute(mqttMessageSender);
        }
    }

    public void publishMsg(String topic, String msg) {
        if (enable) {
            try {
                persistentFileService.persistMessage(topic, msg.getBytes(StandardCharsets.UTF_8));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void subscribeMsg(String topic) {
        if (enable) {
            mqttBrokerMonitor.subscribe(topic, new PrintMessageListener());
        }
    }

    public void subscribeMsg(String topic, BaseCoverMessageListener listener) {
        if (enable) {
            mqttBrokerMonitor.subscribe(topic, listener);
        }
    }

    public void unsubscribeMsg(String topic) {
        if (enable) {
            mqttBrokerMonitor.unsubscribe(topic);
        }
    }

    private void waitWithTimeout(Future future) throws Exception {
        if (enable) {
            future.get(OPERATION_TIMEOUT_IN_SEC, TimeUnit.SECONDS);
        }
    }
}
